<template>
  <!-- 管理员专用的文章列表 -->
  <div>
    <div class="flex justify-between items-center mb-6">
      <h1 class="text-2xl font-bold text-gray-900">文章管理</h1>
      <router-link to="/admin/articles/new" class="inline-flex items-center px-4 py-2 border border-transparent text-sm font-medium rounded-md shadow-sm text-white bg-[#C32A31] hover:bg-[#991E29] focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-[#C32A31]">
        新建文章
      </router-link>
    </div>

    <!-- 搜索组件 -->
    <AdminSearchBar :initial-keyword="searchKeyword" @search="searchArticles" />

    <!-- 加载状态 -->
    <div v-if="loading" class="flex justify-center items-center py-12">
      <svg class="animate-spin h-8 w-8 text-[#C32A31]" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24">
        <circle class="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" stroke-width="4"></circle>
        <path class="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"></path>
      </svg>
    </div>

    <!-- 错误信息 -->
    <div v-else-if="error" class="bg-red-50 border-l-4 border-red-400 p-4 mb-6">
      <div class="flex">
        <div class="flex-shrink-0">
          <svg class="h-5 w-5 text-red-400" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 20 20" fill="currentColor" aria-hidden="true">
            <path fill-rule="evenodd" d="M10 18a8 8 0 100-16 8 8 0 000 16zM8.707 7.293a1 1 0 00-1.414 1.414L8.586 10l-1.293 1.293a1 1 0 101.414 1.414L10 11.414l1.293 1.293a1 1 0 001.414-1.414L11.414 10l1.293-1.293a1 1 0 00-1.414-1.414L10 8.586 8.707 7.293z" clip-rule="evenodd" />
          </svg>
        </div>
        <div class="ml-3">
          <p class="text-sm text-red-700">{{ error }}</p>
        </div>
      </div>
    </div>

    <!-- 文章列表 -->
    <div v-else-if="articles.length > 0" class="bg-white shadow overflow-hidden sm:rounded-md">
      <ul class="divide-y divide-gray-200">
        <li v-for="article in articles" :key="article.newsId" class="hover:bg-gray-50 transition-colors duration-150">
          <div class="px-4 py-4 sm:px-6">
            <div class="flex items-center justify-between">
              <div class="flex items-center">
                <p class="text-sm font-medium text-[#C32A31] truncate">
                  <router-link :to="`/news/${article.newsId}`" target="_blank" class="hover:underline">
                    {{ article.title }}
                  </router-link>
                </p>
                <p class="ml-2 flex-shrink-0 inline-block px-2 py-0.5 text-xs font-medium bg-green-100 text-green-800 rounded-full">{{ article.category }}</p>
              </div>
              <div class="ml-2 flex-shrink-0 flex">
                <router-link :to="`/admin/articles/edit/${article.newsId}`" class="mr-2 inline-flex items-center px-3 py-1 border border-transparent text-xs font-medium rounded-md text-white bg-[#C32A31] hover:bg-[#991E29] focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-[#C32A31]">
                  <svg xmlns="http://www.w3.org/2000/svg" class="h-4 w-4 mr-1" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M11 5H6a2 2 0 00-2 2v11a2 2 0 002 2h11a2 2 0 002-2v-5m-1.414-9.414a2 2 0 112.828 2.828L11.828 15H9v-2.828l8.586-8.586z" />
                  </svg>
                  编辑
                </router-link>
                <button @click="confirmDelete(article)" class="inline-flex items-center px-3 py-1 border border-transparent text-xs font-medium rounded-md text-white bg-red-600 hover:bg-red-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-red-500">
                  <svg xmlns="http://www.w3.org/2000/svg" class="h-4 w-4 mr-1" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16" />
                  </svg>
                  删除
                </button>
              </div>
            </div>
            <div class="mt-2 sm:flex sm:justify-between">
              <div class="sm:flex">
                <p class="flex items-center text-sm text-gray-500">
                  <svg class="flex-shrink-0 mr-1.5 h-5 w-5 text-gray-400" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 20 20" fill="currentColor">
                    <path fill-rule="evenodd" d="M4 4a2 2 0 012-2h4.586A2 2 0 0112 2.586L15.414 6A2 2 0 0116 7.414V16a2 2 0 01-2 2H6a2 2 0 01-2-2V4zm2 6a1 1 0 011-1h6a1 1 0 110 2H7a1 1 0 01-1-1zm1 3a1 1 0 100 2h6a1 1 0 100-2H7z" clip-rule="evenodd" />
                  </svg>
                  ID: {{ article.newsId }}
                </p>
              </div>
              <div class="mt-2 flex items-center text-sm text-gray-500 sm:mt-0">
                <svg class="flex-shrink-0 mr-1.5 h-5 w-5 text-gray-400" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 20 20" fill="currentColor">
                  <path fill-rule="evenodd" d="M6 2a1 1 0 00-1 1v1H4a2 2 0 00-2 2v10a2 2 0 002 2h12a2 2 0 002-2V6a2 2 0 00-2-2h-1V3a1 1 0 10-2 0v1H7V3a1 1 0 00-1-1zm0 5a1 1 0 000 2h8a1 1 0 100-2H6z" clip-rule="evenodd" />
                </svg>
                <p>
                  发布时间: {{ formatDate(article.pubTime) }}
                </p>
              </div>
            </div>
          </div>
        </li>
      </ul>
    </div>

    <!-- 无数据提示 -->
    <div v-else class="bg-white shadow overflow-hidden sm:rounded-md p-6 text-center">
      <p class="text-gray-500">暂无文章数据</p>
    </div>

    <!-- 分页控件 -->
    <div v-if="articles.length > 0" class="mt-6 flex justify-center">
      <nav class="relative z-0 inline-flex rounded-md shadow-sm -space-x-px" aria-label="Pagination">
        <button
          @click="changePage(currentPage - 1)"
          :disabled="currentPage <= 1"
          class="relative inline-flex items-center px-2 py-2 rounded-l-md border border-gray-300 bg-white text-sm font-medium text-gray-500 hover:bg-gray-50"
          :class="{ 'opacity-50 cursor-not-allowed': currentPage <= 1 }"
        >
          <span class="sr-only">上一页</span>
          <svg class="h-5 w-5" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 20 20" fill="currentColor" aria-hidden="true">
            <path fill-rule="evenodd" d="M12.707 5.293a1 1 0 010 1.414L9.414 10l3.293 3.293a1 1 0 01-1.414 1.414l-4-4a1 1 0 010-1.414l4-4a1 1 0 011.414 0z" clip-rule="evenodd" />
          </svg>
        </button>
        <span class="relative inline-flex items-center px-4 py-2 border border-gray-300 bg-white text-sm font-medium text-gray-700">
          第 {{ currentPage }} / {{ totalPages }} 页
        </span>
        <button
          @click="changePage(currentPage + 1)"
          :disabled="!hasMorePages"
          class="relative inline-flex items-center px-2 py-2 rounded-r-md border border-gray-300 bg-white text-sm font-medium text-gray-500 hover:bg-gray-50"
          :class="{ 'opacity-50 cursor-not-allowed': !hasMorePages }"
        >
          <span class="sr-only">下一页</span>
          <svg class="h-5 w-5" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 20 20" fill="currentColor" aria-hidden="true">
            <path fill-rule="evenodd" d="M7.293 14.707a1 1 0 010-1.414L10.586 10 7.293 6.707a1 1 0 011.414-1.414l4 4a1 1 0 010 1.414l-4 4a1 1 0 01-1.414 0z" clip-rule="evenodd" />
          </svg>
        </button>
      </nav>
    </div>

    <!-- 删除确认对话框 -->
    <div v-if="showDeleteConfirm" class="fixed z-10 inset-0 overflow-y-auto" aria-labelledby="modal-title" role="dialog" aria-modal="true">
      <div class="flex items-end justify-center min-h-screen pt-4 px-4 pb-20 text-center sm:block sm:p-0">
        <div class="fixed inset-0 bg-gray-500 bg-opacity-75 transition-opacity" aria-hidden="true"></div>
        <span class="hidden sm:inline-block sm:align-middle sm:h-screen" aria-hidden="true">&#8203;</span>
        <div class="inline-block align-bottom bg-white rounded-lg text-left overflow-hidden shadow-xl transform transition-all sm:my-8 sm:align-middle sm:max-w-lg sm:w-full">
          <div class="bg-white px-4 pt-5 pb-4 sm:p-6 sm:pb-4">
            <div class="sm:flex sm:items-start">
              <div class="mx-auto flex-shrink-0 flex items-center justify-center h-12 w-12 rounded-full bg-red-100 sm:mx-0 sm:h-10 sm:w-10">
                <svg class="h-6 w-6 text-red-600" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke="currentColor" aria-hidden="true">
                  <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-3L13.732 4c-.77-1.333-2.694-1.333-3.464 0L3.34 16c-.77 1.333.192 3 1.732 3z" />
                </svg>
              </div>
              <div class="mt-3 text-center sm:mt-0 sm:ml-4 sm:text-left">
                <h3 class="text-lg leading-6 font-medium text-gray-900" id="modal-title">
                  确认删除
                </h3>
                <div class="mt-2">
                  <p class="text-sm text-gray-500">
                    您确定要删除文章 "{{ articleToDelete?.title }}" 吗？此操作无法撤销。
                  </p>
                </div>
              </div>
            </div>
          </div>
          <div class="bg-gray-50 px-4 py-3 sm:px-6 sm:flex sm:flex-row-reverse">
            <button @click="deleteArticle" type="button" class="w-full inline-flex justify-center rounded-md border border-transparent shadow-sm px-4 py-2 bg-red-600 text-base font-medium text-white hover:bg-red-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-red-500 sm:ml-3 sm:w-auto sm:text-sm">
              删除
            </button>
            <button @click="showDeleteConfirm = false" type="button" class="mt-3 w-full inline-flex justify-center rounded-md border border-gray-300 shadow-sm px-4 py-2 bg-white text-base font-medium text-gray-700 hover:bg-gray-50 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-indigo-500 sm:mt-0 sm:ml-3 sm:w-auto sm:text-sm">
              取消
            </button>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, computed } from 'vue';
import { articleApi } from '../../utils/api';
import AdminSearchBar from './AdminSearchBar.vue';
import { useRoute, useRouter } from 'vue-router';

const route = useRoute();
const router = useRouter();

// 状态
const loading = ref(true);
const error = ref(null);
const articles = ref([]);
const showDeleteConfirm = ref(false);
const articleToDelete = ref(null);
const searchKeyword = ref('');
const currentPage = ref(1);
const pageSize = ref(10);
const totalPages = ref(1); // 总页数

// 计算属性
const hasMorePages = computed(() => {
  return currentPage.value < totalPages.value;
});

// 处理分页数据
const handlePaginationData = (result) => {
  //console返回请求到的数据
  console.log('handlePaginationData:', result);
  //{list: Array(10), total: 67, pageNum: 1, pageSize: 10, pages: 7} 会被判定为请求失败!

  // 检查响应是否为空或非对象
  if (!result || typeof result !== 'object') {
    console.error('Invalid response format:', result);
    return false;
  }

  // 情况1: 直接返回分页对象 {list: [...], total: number, pageNum: number, pageSize: number, pages: number}
  if (result.list && Array.isArray(result.list)) {
    articles.value = result.list;
    totalPages.value = result.pages || 1;
    // 不要覆盖currentPage.value，保持用户选择的页码
    // currentPage.value = result.pageNum || 1;
    return true;
  }

  // 情况2: 标准响应格式 {code: 200, data: {...}}
  if (result.code !== undefined) {
    if (result.code !== 200) {
      error.value = result.msg || '请求失败';
      return false;
    }

    // 处理标准响应中的数据
    if (result.data && typeof result.data === 'object') {
      // 如果data是分页对象格式
      if (result.data.list) {
        articles.value = result.data.list || [];
        totalPages.value = result.data.pages || 1;
        // 不要覆盖currentPage.value，保持用户选择的页码
        // currentPage.value = result.data.pageNum || 1;
      } else if (Array.isArray(result.data)) {
        // 如果data是数组
        articles.value = result.data;
      } else {
        // 其他对象格式
        articles.value = [];
      }
      return true;
    } else if (Array.isArray(result.data)) {
      // 直接返回数组
      articles.value = result.data;
      return true;
    }
  }

  // 情况3: 直接返回数组
  if (Array.isArray(result)) {
    articles.value = result;
    return true;
  }

  // 情况4: 未知格式
  console.warn('Unexpected response format:', result);
  articles.value = [];
  return false;
};

// 获取文章列表
const fetchArticles = async () => {
  loading.value = true;
  error.value = null;

  try {
    // 如果有搜索关键词，则使用搜索API
    if (searchKeyword.value) {
      await searchArticles(searchKeyword.value);
      return;
    }

    // 否则获取所有文章
    const result = await articleApi.getArticleList({
      limit: pageSize.value,
      page: currentPage.value
    });

    // 处理响应数据，不抛出异常
    handlePaginationData(result);
  } catch (err) {
    console.error('Error fetching articles:', err);
    error.value = '获取文章列表失败，请稍后再试';
  } finally {
    loading.value = false;
  }
};

// 搜索文章
const searchArticles = async (keyword) => {
  if (!keyword) return;

  searchKeyword.value = keyword;
  loading.value = true;
  error.value = null;

  try {
    // 调用管理员专用搜索API
    const result = await articleApi.adminSearchArticles(keyword, currentPage.value, pageSize.value);

    // 处理响应数据
    const success = handlePaginationData(result);

    // 如果处理成功，更新URL参数
    if (success) {
      // 更新URL参数，但不重新加载页面
      router.replace({
        query: {
          ...route.query,
          keyword,
          page: currentPage.value
        }
      });
    }
  } catch (err) {
    console.error('Error searching articles:', err);
    error.value = '搜索文章失败，请稍后再试';
  } finally {
    loading.value = false;
  }
};

// 格式化日期
const formatDate = (dateString) => {
  if (!dateString) return '';

  const date = new Date(dateString);
  return date.toLocaleString();
};

// 确认删除
const confirmDelete = (article) => {
  articleToDelete.value = article;
  showDeleteConfirm.value = true;
};

// 删除文章
const deleteArticle = async () => {
  if (!articleToDelete.value) return;

  try {
    const result = await articleApi.deleteArticle(articleToDelete.value.newsId);

    if (result.code === 200) {
      // 删除成功，更新列表
      articles.value = articles.value.filter(a => a.newsId !== articleToDelete.value.newsId);
    } else {
      error.value = result.msg || '删除文章失败';
    }
  } catch (err) {
    console.error('Error deleting article:', err);
    error.value = '删除文章失败，请稍后再试';
  } finally {
    showDeleteConfirm.value = false;
    articleToDelete.value = null;
  }
};

// 切换页码
const changePage = (page) => {
  // 验证页码范围
  if (page < 1) return;
  if (page > totalPages.value) return;

  currentPage.value = page;

  // 更新URL参数
  router.replace({
    query: {
      ...route.query,
      page
    }
  });

  // 如果有搜索关键词，则执行搜索，否则获取所有文章
  if (searchKeyword.value) {
    searchArticles(searchKeyword.value);
  } else {
    fetchArticles();
  }
};

// 检查URL中是否有搜索参数
const checkUrlParams = () => {
  const keyword = route.query.keyword;
  if (keyword) {
    searchKeyword.value = keyword;
  }

  const page = parseInt(route.query.page);
  if (page && !isNaN(page) && page > 0) {
    currentPage.value = page;
  }
};

// 页面加载时获取文章列表
onMounted(() => {
  checkUrlParams();
  fetchArticles();
});
</script>

<style scoped>
/* 可以添加自定义样式 */
</style>
